<?php

namespace App\Admin\Controllers\Core;

use App\Admin\Actions\Message\CleanAll;
use App\Admin\Actions\Message\MarkAllAsRead;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Routing\Controller;

class MessageController extends Controller
{
    public function index(Content $content): Content
    {
        return $content->header('用户消息')
            ->description('列表')
            ->body($this->grid());
    }

    public function grid(): Grid
    {
        $model = DatabaseNotification::whereMorphedTo('notifiable', Admin::user())->latest();

        return Grid::make($model, function (Grid $grid) {
            $grid->tools([new MarkAllAsRead, new CleanAll]);

            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->disableViewButton(false);
            $grid->disableBatchDelete(false);

            $grid->column('消息标题')
                ->display(function () {
                    if (method_exists($this->type, 'getTitle')) {
                        return $this->type::getTitle();
                    } else {
                        return $this->type;
                    }
                })
                ->link(fn() => route('admin.messages.show', $this->id), '_self');
            $grid->column('created_at')
                ->dateFormat();
            $grid->column('read_at')
                ->dateFormat();
        });
    }

    public function show(Content $content, DatabaseNotification $notification): Content
    {
        $notification->markAsRead();

        return $content->header(
            method_exists($notification->type, 'getTitle') ?
                $notification->type::getTitle() :
                $notification->type
        )
            ->description('消息详情')
            ->body(view('admin.message', ['notification' => $notification]));
    }

    public function destroy(string $id)
    {
        return $this->form()->destroy($id);
    }

    public function form(): Form
    {
        return Form::make(DatabaseNotification::class);
    }
}
